package org.csu.mypetstore.controller;


import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Order;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.annotation.SessionScope;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@SessionScope
@Controller
@RequestMapping("/order/")
@SessionAttributes({"order", "cardTypeList","orderList"})
public class OrderController {
    @Autowired
    private OrderService orderService;

    @Autowired
    private CartService cartService;

    private static final List<String> cardTypeList;

    static {
        List<String> cList = new ArrayList<>();
        cList.add("Visa");
        cList.add("MasterCard");
        cList.add("American Express");
        cardTypeList = Collections.unmodifiableList(cList);
    }
    @GetMapping("newOrderForm")
    public String newOrderForm(@SessionAttribute("account") Account account,@SessionAttribute("cart") Cart cart, Model model){
        Order order=new Order();
        order.initOrder(account,cart);
        model.addAttribute("order",order);
        model.addAttribute("cardList",cardTypeList);
        return "order/NewOrderForm";
    }

    @PostMapping("conFirmOrderForm")
    public String conFirmOrderForm(@SessionAttribute("order") Order order,Model model){
        cartService.delete(order.getUsername());

        return "order/ConfirmOrder";
    }

    @GetMapping("viewOrder")
    public String viewOrder(@SessionAttribute("order")Order order,@SessionAttribute("account") Account account,Model model){
        orderService.insertOrder(order);
        System.out.println(order.getOrderId());
        order=orderService.getOrder(order.getOrderId());
        cartService.delete(account.getUsername());
        Cart cart=new Cart();
        model.addAttribute("cart",cart);
        model.addAttribute("order",order);
        return "order/ViewOrder";
    }
    @GetMapping("viewOldOrder")
    public String viewOldOrder(int orderId, @SessionAttribute("account") Account account,Model model){
        Order order=orderService.getOrder(orderId);
        model.addAttribute("order",order);
        return "order/ViewOrder";
    }

    @GetMapping("viewListOrder")
    public String viewListOrder(@SessionAttribute("account") Account account, Model model ){
        List<Order> orderList=orderService.getOrdersByUsername(account.getUsername());
        model.addAttribute("orderList",orderList);
        return "order/ListOrder" ;
    }
}
